package com.atldy.cloudgrains.advice;

import com.atldy.common.vo.ResultResponse;
import com.atldy.cloudgrains.annotation.IgnoreResponseAdvice;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @version 1.0
 * @Author: li-dong-yang
 * @CreateTime: 2021-09-15 17:05
 * @Description： 全局通用响应
 */
@RestControllerAdvice(basePackages = "com.atldy.cloudgrains")
public class CommonResponceAdvice implements ResponseBodyAdvice<Object> {

    /**
     * <h3>是否调用beforeBodyWrite</h3>
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class) ||
                methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)) {

            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        ResultResponse<Object> response = new ResultResponse<>(0, "");
        if (o == null) {
            return response;
        } else if (o instanceof ResultResponse) {
            response = (ResultResponse<Object>) o;
        } else {
            response.setData(o);
        }
        return response;
    }
}